package cn.itcast.search.service.impl;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.hmall.dto.common.PageDTO;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.search.SearchReqDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.item.ItemDoc;
import cn.itcast.search.config.EsConfig;
import cn.itcast.search.service.SearchService;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.fetch.subphase.highlight.Highlighter;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.xml.ws.Holder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private EsConfig esConfig;
    @Autowired
    private ItemClient itemClient;

    /**
     * 批量导入es
     *
     * @return
     */
    @Override
    public ResultDTO searchData() {
        for (int i = 1; i < 900; i++) {
            PageDTO<Item> page = itemClient.selectAllPage(i);
            List<Item> list = page.getList();
            if (list.size() == 0) {
                break;
            }
            // 1.创建Request
            BulkRequest request = new BulkRequest();
            for (Item item : list) {
                //转换文档类型
                ItemDoc itemDoc = new ItemDoc(item);
                //变为JSON格式
                String json = JSON.toJSONString(itemDoc);
                //创建新增文档的Request对象
                request.add(new IndexRequest("item").source(json, XContentType.JSON));
            }
            //调用客户端请求
            bulk(request);
        }
        return ResultDTO.ok();
    }

    /**
     * 搜索栏自动补全
     *
     * @param key
     * @return
     */
    @Override
    public List<String> searchSuggestion(String key) {
        //创建request对象
        SearchRequest request = new SearchRequest("item");
        SearchSourceBuilder source = request.source();
        //条件
        source.suggest(new SuggestBuilder()
                .addSuggestion("suggestions", SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(key)
                        .skipDuplicates(true)
                        .size(10)));
        //相应请求
        try {
            SearchResponse response = esConfig.client().search(request, RequestOptions.DEFAULT);
            //解析相应结果，根据相应名字，补全响应结果
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //新建一个集合
            List<String> list = new ArrayList<>(options.size());
            //遍历options
            for (CompletionSuggestion.Entry.Option option : options) {
                //获取文本
                String text = option.getText().toString();
                //添加到list集合
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("搜索异常");
        }
    }

    /**
     * 过滤项聚合功能
     *
     * @return
     */
    @Override
    public Map<String, List<String>> searchFilters(SearchReqDTO searchReqDTO) {
        //创建request对象
        SearchRequest request = new SearchRequest("item");
        SearchSourceBuilder source = request.source();
        //通过布尔查询
        bool(searchReqDTO,source);
        source.size(0);
        //封装分组
        aggregation(source);
        //调用客户端
        try {
            SearchResponse response = esConfig.client().search(request, RequestOptions.DEFAULT);
            //解析响应结果
            Aggregations aggregations = response.getAggregations();
            Map<String, List<String>> map = new HashMap<>();
            //封装返回数据
            List<String> brandAgg =getAggName(aggregations,"brandAgg");
            //品牌
            map.put("brand",brandAgg);
            List<String> categoryAgg =getAggName(aggregations,"categoryAgg");
            //分类
            map.put("category",categoryAgg);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("搜索异常");
        }
    }

    /**
     * 基本搜索功能
     * @param searchReqDTO
     * @return
     */
    @Override
    public PageDTO<ItemDoc> searchList(SearchReqDTO searchReqDTO) {
        //创建request对象
        SearchRequest request = new SearchRequest("item");
        SearchSourceBuilder source = request.source();
        //复杂查询
        bool(searchReqDTO,source);
        //设置分页
        source.from((searchReqDTO.getPage()-1)*searchReqDTO.getPage()).size(searchReqDTO.getSize());
        //响应请求
        try {
            SearchResponse response = esConfig.client().search(request, RequestOptions.DEFAULT);
             PageDTO pageDTO = handleResponse(response);
            return pageDTO;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增商品
     * @param id
     */
    @Override
    public void insertById(Long id) {
        if("".equals(id)||id==null){
            throw new RuntimeException("id不能为空");
        }
        // 0.根据id查询酒店数据
        Item item = itemClient.selectItemById(id);
        // 转换为文档类型
        ItemDoc itemDoc = new ItemDoc(item);
        // 1.准备Request对象
        IndexRequest request = new IndexRequest("item").id(item.getId().toString());
        // 2.准备Json文档
        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
        // 3.发送请求
        try {
            esConfig.client().index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("id搜索异常");
        }
    }

    /**
     * 删除商品
     */
    @Override
    public void deleteById(Long id) {
        if("".equals(id)||id==null){
            throw new RuntimeException("id不能为空");
        }
        // 1.准备Request
        DeleteRequest request = new DeleteRequest("item", id.toString());
        //发送请求
        try {
            esConfig.client().delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("删除异常");
        }
    }

    /**
     * 上架
     */
    @Override
    public void upById(Long id) {
        if("".equals(id)||id==null){
            throw new RuntimeException("id不能为空");
        }
        //通过feign根据id获的商品信息
        Item item = itemClient.selectItemById(id);
        // 转换为文档类型
        ItemDoc itemDoc = new ItemDoc(item);
        // 1.准备Request对象
        IndexRequest request = new IndexRequest("item").id(item.getId().toString());
        // 2.准备Json文档
        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
        try {
            esConfig.client().index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("id搜索异常");
        }
    }

    /**
     * 下架
     * @param id
     */
    @Override
    public void downById(Long id) {
        if("".equals(id)||id==null){
            throw new RuntimeException("id不能为空");
        }
        //通过feign根据id获的商品信息
        Item item = itemClient.selectItemById(id);
        // 转换为文档类型
        ItemDoc itemDoc = new ItemDoc(item);
        // 1.准备Request对象
        IndexRequest request = new IndexRequest("item").id(item.getId().toString());
        // 2.准备Json文档
        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
        try {
            esConfig.client().index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("id搜索异常");
        }
    }

    /**
     * 解析响应结果
     * @param response
     * @return
     */
    private PageDTO handleResponse(SearchResponse response){
        //查询条数
        long total = response.getHits().getTotalHits().value;
        PageDTO pageDTO = new PageDTO();
        //创建List集合
        List<ItemDoc> list = new ArrayList<>();
        pageDTO.setTotal(total);
        //遍历
        for (SearchHit hit : response.getHits()) {
            //转换格式
            ItemDoc itemDoc = JSON.parseObject(hit.getSourceAsString(), ItemDoc.class);
            //高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(!CollectionUtils.isEmpty(highlightFields)){
                //根据字段名获得高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if(highlightField!=null){
                    itemDoc.setName(highlightField.getFragments()[0].string());
                }
            }
            //将数据存入集合中
            list.add(itemDoc);
        }
        //将集合存入pageResult
        pageDTO.setList(list);
       return pageDTO;
    }
    /**
     *相应分组
     * @param aggregations
     * @param name
     * @return
     */
    public List<String> getAggName(Aggregations aggregations,String name){
        Terms terms = aggregations.get(name);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            list.add(bucket.getKeyAsString());
        }
        return list;
    }
    /**
     * 封装分组
     * @param source
     */
    public void aggregation(SearchSourceBuilder source){
        source.aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(5));
        source.aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(5));
    }
    /**
     * 布尔查询
     *
     * @param searchReqDTO
     * @param source
     */
    public void bool(SearchReqDTO searchReqDTO, SearchSourceBuilder source) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //判断searchReqDTO.getKey的值是否为空
        if (StringUtils.isNotBlank(searchReqDTO.getKey())) {
            //不为空按照条件查询
            MatchQueryBuilder name = QueryBuilders.matchQuery("all", searchReqDTO.getKey());
            //必须查询
            boolQueryBuilder.must(name);
            //高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("name").requireFieldMatch(false);
            highlightBuilder.preTags("<em>");
            highlightBuilder.postTags("</em>");
            source.highlighter(highlightBuilder);
        } else {
            //查询全部
            MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
            boolQueryBuilder.must(matchAllQueryBuilder);
        }
        //判断sortBy都有什么字段1.default(默认) 2.score(评分) 3.price(价格)
        if (searchReqDTO.getSortBy().equals("score")) {
            source.sort("score", SortOrder.DESC);
        } else if (searchReqDTO.getSortBy().equals("price")) {
            source.sort("price", SortOrder.ASC);
        }
        //过滤 1.分类 2.品牌 3.价格
        //分类
        if (StringUtils.isNotBlank(searchReqDTO.getCategory())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", searchReqDTO.getCategory()));
        }
        //品牌
        if (StringUtils.isNotBlank(searchReqDTO.getBrand())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", searchReqDTO.getBrand()));
        }
        //价格
        if (searchReqDTO.getMaxPrice() != null && searchReqDTO.getMinPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(searchReqDTO.getMinPrice()).lte(searchReqDTO.getMaxPrice()));
        }
        //算分查询
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                //原始查询,相关性算分的查询
                boolQueryBuilder,
                //// function score的数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件 广告位
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
                //相加
        ).boostMode(CombineFunction.SUM);
        source.query(functionScoreQueryBuilder);
    }

    /**
     * 调用客户端请求
     *
     * @param request
     * @return
     */
    public BulkResponse bulk(BulkRequest request) {
        try {
            BulkResponse bulk = esConfig.client().bulk(request, RequestOptions.DEFAULT);
            return bulk;
        } catch (IOException e) {
            throw new RuntimeException("异常错误");
        }
    }
}
